<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      div {
        width: 50px;
        height: 50px;
        float: left;
        margin: 10px;
        background-color: red;
      }
    </style>
  </head>
  <body>
    <div>a</div>
    <div>b</div>
    <div>c</div>
    <div>d</div>
    <div>e</div>
    <div>f</div>
    <div>g</div>
    <div>h</div>
    <div>i</div>
    <div>j</div>
    <script>
      /*  let divs = document.querySelectorAll('div')
      for (let i = 0; i < divs.length; i++) {
        divs[i].addEventListener('click', function () {
          alert(i)
        })
      } */

      //闭包实现
      let divs = document.querySelectorAll('div')
      for (var i = 0; i < divs.length; i++) {
        ;(function (index) {
          divs[index].addEventListener('click', function () {
            alert(index)
          })
        })(i)
      }
    </script>
  </body>
</html>
